<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>循环加载</title>
</head>
<body>
    <h1>循环加载</h1>
    <h2>模块之间相互依赖的处理</h2>

    <script type="module">
        // ES6模块的循环加载
        // a.js
        import { bar } from './b.js';
        export function foo() {
            console.log('foo');
            bar();
            console.log('执行完毕');
        }

        // b.js
        import { foo } from './a.js';
        export function bar() {
            console.log('bar');
            if (Math.random() > 0.5) {
                foo();
            }
        }

        // CommonJS的循环加载
        /*
        // a.js
        exports.done = false;
        const b = require('./b.js');
        console.log('在 a.js 中，b.done = %j', b.done);
        exports.done = true;
        console.log('a.js 执行完毕');

        // b.js
        exports.done = false;
        const a = require('./a.js');
        console.log('在 b.js 中，a.done = %j', a.done);
        exports.done = true;
        console.log('b.js 执行完毕');
        */

        // 实际应用示例
        // user.js
        import { Post } from './post.js';
        export class User {
            constructor(name) {
                this.name = name;
                this.posts = [];
            }

            addPost(title) {
                const post = new Post(title, this);
                this.posts.push(post);
                return post;
            }
        }

        // post.js
        import { User } from './user.js';
        export class Post {
            constructor(title, author) {
                this.title = title;
                this.author = author;
            }

            static createPost(title, authorName) {
                const author = new User(authorName);
                return author.addPost(title);
            }
        }

        // 使用示例
        const user = new User('张三');
        const post = user.addPost('第一篇文章');
        console.log(post.author.name); // '张三'
        console.log(user.posts[0].title); // '第一篇文章'
    </script>
</body>
</html> 